<!--
  @author:  long
  @date:    2024/5/29
  @file:    xx
  @require:
-->
<template>
  <div class="createWorkItem">
    <el-dialog
      v-model="dialogVisible"
      title="新建工作项"
      width="93vw"
      destroy-on-close
      :before-close="handleClose"
    >
      <el-form
        label-position="top"
        label-width="auto"
        :model="workItemForm"
        ref="workItemFormRef"
        :rules="rules"
      >
        <el-row :gutter="20">
          <el-col :span="17" style="height: 67vh; overflow: auto">
            <el-form-item label="标题" prop="title">
              <el-input
                v-model="workItemForm.title"
                placeholder="输入标题"
                maxlength="255"
                show-word-limit
                style="width: 100%"
              ></el-input>
            </el-form-item>
            <el-form-item label="描述">
              <editor
                class="w-full"
                v-model="workItemForm.description"
                :min-height="180"
              />
            </el-form-item>

            <el-form-item
              label="上传附件"
              prop="fileList"
              v-model:file-list="workItemForm.fileList"
            >
              <el-upload
                class="upload-demo"
                action="#"
                :before-upload="beforeAvatarUpload"
                :http-request="requestFile"
                accept=".rar, .zip, .doc, .docx, .pdf, .xls, .xlsx, .ppt,
              .pptx,.gif, .jpg, .jpeg, .png"
                :limit="10"
                :show-file-list="false"
              >
                <el-button type="primary" style="font-size: 14px">
                  <el-icon>
                    <UploadFilled />
                  </el-icon>
                  添加附件
                </el-button>
                <template #tip>
                  <div class="el-upload__tip float-right pl-5px">
                    支持格式.rar .zip .doc .docx .pdf ，单个文件不能超过200MB
                  </div>
                </template>
              </el-upload>
              <div class="text-14px mt-10px" style="width: 100%">
                <div
                  v-for="(item, index) in formData.fileList"
                  :key="item.fileName"
                >
                  <el-link :href="item.url" :underline="false" type="primary"
                    >{{ item.origFileName }}
                  </el-link>
                  <el-button text plain @click="delFileName(index)"
                    >删除
                  </el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>

          <el-divider direction="vertical"></el-divider>
          <el-col :span="6" style="height: 67vh; overflow: auto">
            <el-form-item label="项目" prop="projectId">
              <el-select
                v-model="workItemForm.projectId"
                filterable
                placeholder="项目"
                class="w-full"
                disabled
              >
                <template #prefix>
                  <img class="mr-5px" :src="scrumFill" alt="" />
                </template>
                <el-option
                  v-for="item in projectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="工作项类型" prop="workItemType">
              <el-select
                v-model="workItemForm.workItemType"
                filterable
                placeholder="工作项类型"
                class="w-full"
                @change="handleWorkItemTypeChange"
              >
                <template #prefix>
                  <img
                    class="mr-5px"
                    :src="selectIcon[workItemForm.workItemType]"
                    alt=""
                  />
                </template>
                <el-option
                  v-for="(dict, index) in project_work_item"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                >
                  <div class="flex items-center">
                    <img class="mr-5px" :src="selectIcon[dict.value]" alt="" />

                    <span>{{ dict.label }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="workItemForm.workItemType != 'epic'"
              label="父工作项"
            >
              <el-select
                v-model="workItemForm.parentId"
                filterable
                remote
                reserve-keyword
                placeholder="父工作项"
                :loading="parentLoading"
                clearable
                no-data-text="无匹配数据"
                :remote-method="parentWorkItemRemoteMethod"
                class="w-full"
              >
                <template #prefix v-if="workItemForm.parentId != ''">
                  <img
                    class="mr-5px"
                    :src="selectIcon[parentIconType]"
                    alt=""
                  />
                </template>
                <el-option
                  v-for="item in parentWorkItemOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <div class="flex items-center">
                    <img
                      class="mr-5px"
                      :src="selectIcon[parentIconType]"
                      alt=""
                    />

                    <span>{{ item.label }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="负责人">
              <el-select
                v-model="workItemForm.directorId"
                placeholder="负责人"
                @focus="userInputFocus"
                class="w-full"
              >
                <el-option
                  v-for="(item, index) in selectOptionObj['directorId']"
                  :key="index"
                  :label="item.label"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="workItemForm.startDate"
                type="date"
                placeholder="开始时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled-date="startDisabledDate"
              />
            </el-form-item>
            <el-form-item label="截止时间">
              <el-date-picker
                v-model="workItemForm.endDate"
                type="date"
                placeholder="截止时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled-date="endDisabledDate"
              />
            </el-form-item>
            <el-form-item label="优先级">
              <el-select
                v-model="workItemForm.priority"
                filterable
                placeholder="优先级"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="(dict, index) in project_backlog_priority"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="风险"
              v-if="
                workItemForm.workItemType != 'task' &&
                workItemForm.workItemType != 'defect'
              "
            >
              <el-select
                v-model="workItemForm.risk"
                filterable
                placeholder="风险"
                clearable
                style="width: 100%"
              >
                <template #prefix v-if="workItemForm.risk != ''">
                  <div
                    :class="[
                      'w8px',
                      'h8px',
                      'rounded-full',
                      'riskColor' + workItemForm.risk
                    ]"
                  ></div>
                </template>
                <el-option
                  v-for="(dict, index) in project_risk_level"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                >
                  <div class="flex items-center">
                    <div
                      :class="[
                        'w8px',
                        'h8px',
                        'rounded-full',
                        'mr-5px',
                        'riskColor' + dict.value
                      ]"
                    ></div>
                    {{ dict.label }}
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            <!--            <el-form-item-->
            <!--              v-if="-->
            <!--                workItemForm.workItemType == 'userStory' ||-->
            <!--                workItemForm.workItemType == 'defect'-->
            <!--              "-->
            <!--              label="故事点"-->
            <!--            >-->
            <!--              <el-input-number-->
            <!--                controls-position="right"-->
            <!--                class="w-full"-->
            <!--                v-model="workItemForm.storyPoints"-->
            <!--                :min="0"-->
            <!--              ></el-input-number>-->
            <!--            </el-form-item>-->
            <el-form-item
              label="任务类别"
              v-if="workItemForm.workItemType == 'task'"
            >
              <el-select
                v-model="workItemForm.taskType"
                filterable
                placeholder="任务类别"
                style="width: 100%"
                clearable
              >
                <template #prefix v-if="workItemForm.taskType != ''">
                  <div
                    :class="[
                      'taskTypeIcon',
                      'taskTypeColor' + workItemForm.taskType
                    ]"
                  ></div>
                </template>
                <el-option
                  v-for="(dict, index) in project_task_type"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                >
                  <div class="flex items-center">
                    <div
                      :class="[
                        'taskTypeIcon',
                        'mr-5px',
                        'taskTypeColor' + dict.value
                      ]"
                    ></div>
                    {{ dict.label }}
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="需求类型"
              v-if="
                workItemForm.workItemType != 'task' &&
                workItemForm.workItemType != 'defect'
              "
            >
              <el-select
                v-model="workItemForm.requirementType"
                filterable
                placeholder="需求类型"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="(dict, index) in project_backlog_type"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="需求来源"
              v-if="
                workItemForm.workItemType != 'task' &&
                workItemForm.workItemType != 'defect'
              "
            >
              <el-select
                v-model="workItemForm.source"
                filterable
                placeholder="需求类型"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="(dict, index) in project_backlog_source"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="严重程度"
              v-if="workItemForm.workItemType == 'defect'"
            >
              <el-select
                v-model="workItemForm.severity"
                filterable
                placeholder="严重程度"
                style="width: 100%"
                clearable
              >
                <template #prefix v-if="workItemForm.severity != ''">
                  <div
                    :class="[
                      'w8px',
                      'h8px',
                      'rounded-full',
                      'severityColor' + workItemForm.severity
                    ]"
                  ></div>
                </template>
                <el-option
                  v-for="(dict, index) in project_defect_severity"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                >
                  <div class="flex items-center">
                    <div
                      :class="[
                        'w8px',
                        'h8px',
                        'rounded-full',
                        'mr-5px',
                        'severityColor' + dict.value
                      ]"
                    ></div>
                    {{ dict.label }}
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="复现概率"
              v-if="workItemForm.workItemType == 'defect'"
            >
              <el-select
                v-model="workItemForm.recurrent"
                filterable
                placeholder="复现概率"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="(dict, index) in project_defect_recurrent"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="缺陷类别"
              v-if="workItemForm.workItemType == 'defect'"
            >
              <el-select
                v-model="workItemForm.defectType"
                filterable
                placeholder="复现概率"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="(dict, index) in project_defect_type"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" link>取消</el-button>
          <el-button type="primary" @click="handleAddWorkItem">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    ></SelectDialog>
  </div>
</template>

<script setup name="CreateWorkItem">
import { delFile, uploadFile } from '@/api/salesManage/contractManage'
import useUserStore from '@/store/modules/user'
import { getCurrentInstance } from 'vue'

import epicSquareFill from '@/assets/icons/svg/epicSquareFill.svg'
import featureSquareFill from '@/assets/icons/svg/featureSquareFill.svg'
import userStorySquareFill from '@/assets/icons/svg/userStorySquareFill.svg'
import taskSquareFill from '@/assets/icons/svg/taskSquareFill.svg'
import bugSquareFill from '@/assets/icons/svg/bugSquareFill.svg'
import scrumFill from '@/assets/icons/svg/scrumFill.svg'
import useResearchProjectStore from '@/store/modules/researchProject'
import {
  getParentBacklogList,
  savebacklogInfo
} from '@/api/researchManage/backlog'

const selectIcon = ref({
  epic: epicSquareFill,
  feature: featureSquareFill,
  userStory: userStorySquareFill,
  task: taskSquareFill,
  defect: bugSquareFill
})

const { proxy } = getCurrentInstance()
const userStore = useUserStore()
// 字典
const {
  project_backlog_priority, //优先级
  project_risk_level, //风险等级
  project_backlog_source, //来源
  project_backlog_type, //类型
  project_defect_type, //缺陷类型
  project_task_type, //任务类别
  project_work_item, //工作项
  project_defect_severity, //缺陷严重程度
  project_defect_recurrent //缺陷复现概率
} = proxy.useDict(
  'project_backlog_priority',
  'project_risk_level',
  'project_backlog_source',
  'project_backlog_type',
  'project_defect_type',
  'project_task_type',
  'project_work_item',
  'project_defect_severity',
  'project_defect_recurrent'
)
//弹窗打开
const dialogVisible = ref(false)
const workItemFormRef = ref(null)
const dialogParam = ref({}) //人员弹窗配置
const selectOptionObj = ref([]) //人员选择下拉
const projectInfo = ref({}) //项目信息
const parentIconType = ref('') //父级图标

const researchProjectStore = useResearchProjectStore()

onMounted(() => {
  researchProjectStore.getProjectInfo(proxy.$route.query.projectId)
})

watch(
  () => researchProjectStore.projectInfo,
  (newVal, oldVal) => {
    console.info('newVal', newVal)
    console.info('oldVal', oldVal)

    projectInfo.value = JSON.parse(JSON.stringify(newVal))
  }
)

// 工作项表单
const workItemForm = ref({
  projectId: '',
  title: '',
  description: '',
  workItemType: '', //工作项
  directorId: '', //负责人
  parentId: '', //父工作项
  risk: '', //风险等级
  requirementType: '', //需求类型
  source: '', //需求来源
  storyPoints: '', //故事点
  taskType: '', //任务类别
  recurrent: '', //复现概率
  defectType: '', //缺陷类别
  severity: '', //严重程度
  priority: '', //优先级
  startDate: '', //开始时间
  endDate: '' //截止时间
})
// 项目下拉
const projectOptions = ref([])
const rules = ref({
  title: [{ required: true, message: '请输入标题', trigger: 'blur,change' }],
  projectId: [{ required: true, message: '请选择项目', trigger: 'blur' }],
  workItemType: [
    { required: true, message: '请选择工作项类型', trigger: 'blur' }
  ]
})
// 附件对象
const formData = ref({
  fileList: [] //附件
})

// 父工作项下拉选项
const parentWorkItemOptions = ref([])
//父工作项loading
const parentLoading = ref(false)

//  开始
const startDisabledDate = date => {
  if (workItemForm.value.endDate !== '' && workItemForm.value.endDate != null) {
    //结束
    let endDate = new Date(workItemForm.value.endDate).getTime()
    return date >= endDate
  } else {
    return false
  }
}

// 截止
const endDisabledDate = date => {
  if (
    workItemForm.value.startDate !== '' &&
    workItemForm.value.startDate != null
  ) {
    //开始时间
    let startDate = new Date(workItemForm.value.startDate).getTime()

    return date <= startDate
  } else {
    return false
  }
}

//设置父工作项图标
const setParentIcon = type => {
  if (type == 'feature') {
    parentIconType.value = 'epic'
  }
  if (type == 'userStory') {
    parentIconType.value = 'feature'
  }
  if (type == 'task' || type == 'defect') {
    parentIconType.value = 'userStory'
  }
}

// 选择工作项类型
const handleWorkItemTypeChange = item => {
  setParentIcon(item)
  parentWorkItemOptions.value = []
  parentWorkItemRemoteMethod()
}

//新建工作项确认
const handleAddWorkItem = () => {
  let type = workItemForm.value.workItemType
  let params = {}

  switch (type) {
    // 史诗
    case 'epic':
      params = {
        projectId: workItemForm.value.projectId,
        title: workItemForm.value.title,
        description: workItemForm.value.description,
        workItemType: workItemForm.value.workItemType,
        directorId:
          selectOptionObj.value && selectOptionObj.value.directorId
            ? selectOptionObj.value.directorId[0].id
            : '',
        director:
          selectOptionObj.value && selectOptionObj.value.directorId
            ? selectOptionObj.value.directorId[0].label
            : '',
        startDate: workItemForm.value.startDate,
        endDate: workItemForm.value.endDate,
        priority: workItemForm.value.priority,
        risk: workItemForm.value.risk,
        requirementType: workItemForm.value.requirementType,
        source: workItemForm.value.source,
        fileList: formData.value.fileList
      }
      break
    // 特性
    case 'feature':
      params = {
        projectId: workItemForm.value.projectId,
        title: workItemForm.value.title,
        description: workItemForm.value.description,
        workItemType: workItemForm.value.workItemType,
        directorId:
          selectOptionObj.value && selectOptionObj.value.directorId
            ? selectOptionObj.value.directorId[0].id
            : '',
        director:
          selectOptionObj.value && selectOptionObj.value.directorId
            ? selectOptionObj.value.directorId[0].label
            : '',
        startDate: workItemForm.value.startDate,
        endDate: workItemForm.value.endDate,
        priority: workItemForm.value.priority,
        risk: workItemForm.value.risk,
        requirementType: workItemForm.value.requirementType,
        source: workItemForm.value.source,
        parentId: workItemForm.value.parentId,
        fileList: formData.value.fileList
      }
      break
    // 用户故事
    case 'userStory':
      params = {
        projectId: workItemForm.value.projectId,
        title: workItemForm.value.title,
        description: workItemForm.value.description,
        workItemType: workItemForm.value.workItemType,
        directorId:
          selectOptionObj.value && selectOptionObj.value.directorId
            ? selectOptionObj.value.directorId[0].id
            : '',
        director:
          selectOptionObj.value && selectOptionObj.value.directorId
            ? selectOptionObj.value.directorId[0].label
            : '',
        startDate: workItemForm.value.startDate,
        endDate: workItemForm.value.endDate,
        priority: workItemForm.value.priority,
        risk: workItemForm.value.risk,
        requirementType: workItemForm.value.requirementType,
        source: workItemForm.value.source,
        parentId: workItemForm.value.parentId,
        fileList: formData.value.fileList
      }
      break
  }
  workItemFormRef.value.validate(valid => {
    if (valid) {
      savebacklogInfo(params).then(res => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess('新建成功')
          //触发父级queryList
          proxy.$emit('queryList')

          //关闭弹窗
          dialogVisible.value = false
        }
      })
    }
  })
}

//父工作项远程搜索
const parentWorkItemRemoteMethod = query => {
  parentLoading.value = true
  let type = ''
  switch (workItemForm.value.workItemType) {
    case 'feature':
      type = 'epic'
      break
    case 'userStory':
      type = 'feature'
      break
    case 'task':
      type = 'userStory'
      break
    case 'defect':
      type = 'userStory'
      break
  }
  let params = {
    projectId: workItemForm.value.projectId,
    title: query,
    workItemType: type
  }
  getParentBacklogList(params).then(res => {
    parentLoading.value = false
    if (res.data.length > 0) {
      parentWorkItemOptions.value = res.data.map(item => {
        return {
          label: item.title,
          value: item.id
        }
      })
    } else {
      parentWorkItemOptions.value = []
    }
  })
}

// 选择人员
const userInputFocus = () => {
  dialogParam.value.type = 'directorId'
  dialogParam.value.title = '选择负责人'
  dialogParam.value.dataType = 'person'
  dialogParam.value.multiple = false
  dialogParam.value.checkStrictly = false
  dialogParam.value.nodeKey = 'uuid'
  dialogParam.value.apiParams = { deptId: userStore.user.orgId }

  dialogParam.value.defaultCheckedKeys = [workItemForm.value.directorId]
  dialogParam.value.dataType = 'person'
  dialogParam.value.isDialog = true
}

/* 负责人人员确认 */
const selectDialogData = val => {
  switch (val.type) {
    case 'directorId':
      selectOptionObj.value[val.type] = val.selectData
      workItemForm.value.directorId = val.defaultCheckedKeys.toString()
      break
  }
}

/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile) {
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType =
    [
      '.rar',
      '.zip',
      '.doc',
      '.docx',
      '.pdf',
      '.jpg',
      '.png',
      '.gif',
      '.jpeg',
      '.xls',
      '.xlsx'
    ].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 200

  if (!allowType) {
    proxy.$message.error(
      '上传文件只能是.rar、.zip、.doc、.docx、.pdf、.jpg、.png、.gif、.jpeg、.xls、.xlsx格式!'
    )
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 200MB!')
  }
  return allowType && isLt2M
}

// 上传附件
function requestFile(params) {
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  // uploadData.append('bucketName', 'article')
  uploadFile(uploadData).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(`${res.data.origFileName}上传成功`)
      console.log('formData.value==>', formData.value)
      formData.value.fileList.push(res.data)
      console.log('formData.value.fileList==>', formData.value.fileList)
    }
  })
}

// 删除附件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const res = await delFile(formData.value.fileList[index].fileName)
      if (res.code === 200) {
        formData.value.fileList.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}

//初始化工作项
const initWorkItem = () => {
  //   设置项目下拉
  projectOptions.value = [
    { label: projectInfo.value.name, value: projectInfo.value.id }
  ]
  formData.value.fileList = []
  // 工作项表单
  workItemForm.value = {
    projectId: projectInfo.value.id,
    title: '',
    description: '',
    workItemType: '', //工作项
    directorId: '', //负责人
    parentId: '', //父工作项
    risk: '', //风险等级
    requirementType: '', //需求类型
    source: '', //需求来源
    storyPoints: '', //故事点
    taskType: '', //任务类别
    recurrent: '', //复现概率
    defectType: '', //缺陷类别
    severity: '', //严重程度
    priority: '', //优先级
    startDate: '', //开始时间
    endDate: '' //截止时间
  }
}

//弹窗关闭
const handleOpen = type => {
  initWorkItem()
  // 设置初始工作项
  workItemForm.value.workItemType = type
  setParentIcon(type)
  parentWorkItemRemoteMethod()
  dialogVisible.value = true
}
// 弹窗打开
const handleClose = () => {
  dialogVisible.value = false
}

defineExpose({
  handleOpen
})
</script>

<style scoped lang="scss">
.el-divider--vertical {
  height: auto;
}

:deep(.el-dialog:not(.is-fullscreen)) {
  margin-top: 3vh !important;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

.riskColor1 {
  background: #f56c6c;
}

.riskColor2 {
  background: #e6a23c;
}

.riskColor3 {
  background: #909399;
}

.severityColor1 {
  background: #f56c6c;
}

.severityColor2 {
  background: #67c23a;
}

.severityColor3 {
  background: #e6a23c;
}

.severityColor4 {
  background: #909399;
}

.taskTypeIcon {
  display: inline-block;
  box-sizing: border-box;
  border-style: solid;
  background: transparent;
  width: 0;
  height: 0;
  border-width: 5px;
  border-radius: 2px;
}

.taskTypeColor1 {
  border-color: rgba(153, 215, 90, 0.6);
}

.taskTypeColor2 {
  border-color: rgba(45, 188, 255, 0.6);
}

.taskTypeColor3 {
  border-color: rgba(78, 138, 249, 0.6);
}

.taskTypeColor4 {
  border-color: rgba(148, 115, 253, 0.6);
}

.taskTypeColor5 {
  border-color: rgba(249, 105, 170, 0.6);
}

.taskTypeColor6 {
  border-color: rgba(255, 164, 21, 0.6);
}

.taskTypeColor7 {
  border-color: rgba(255, 117, 117, 0.6);
}
</style>
